package main

import (
	"fmt"
	"myblogs/app/http/controller"
	"myblogs/app/http/middleware"
	"myblogs/app/variable"
	_ "myblogs/bootstrap"
	"net/http"
	"path/filepath"

	"github.com/gin-contrib/multitemplate"
	"github.com/gin-gonic/gin"
	_ "github.com/go-sql-driver/mysql"
)

func main() {
	// gin.SetMode(gin.ReleaseMode)
	router := gin.Default()

	router.Use(middleware.Middleware())

	// 设置静态文件目录
	router.Static("/static", "./static")
	router.StaticFile("/favicon.ico", "./static/image/favicon.ico")
	router.StaticFile("/error", "./templates/layouts/404.html")

	// 设置模板目录
	// router.LoadHTMLGlob("templates/**/*")
	router.HTMLRender = loadTemplates("./templates")

	// 首页
	router.GET("/", (&controller.IndexController{}).Index)
	// 文章列表
	router.GET("/archives", (&controller.ArticleController{}).GetArticleListIndex)
	router.GET("/archives/page/:page", (&controller.ArticleController{}).GetArticlePageList)
	router.GET("/categories/:name", (&controller.ArticleController{}).GetArticleByCategory)
	// 文章详情
	router.GET("/archives/:id", (&controller.ArticleController{}).GetArticleInfo)
	articleGroup := router.Group("/p/:id")
	{
		articleGroup.GET(".html", (&controller.ArticleController{}).GetArticleInfo)
	}
	// 标签
	router.GET("/tags", (&controller.TagController{}).Index)
	router.GET("/tags/:tag", (&controller.TagController{}).GetArticleByTag)
	// 友链
	router.GET("/links", (&controller.LinkController{}).Index)
	// 关于我
	router.GET("/about", (&controller.AboutController{}).Index)
	// 搜索页
	router.GET("/search", (&controller.SearchController{}).Index)

	// 加载更多文章数据接口
	router.GET("/api/content/posts", (&controller.SearchController{}).Search)
	// 点赞接口
	router.GET("/api/article/like/:id", (&controller.ArticleController{}).ClickLike)

	// 404错误页面设置
	router.NoRoute(func(ctx *gin.Context) {
		// fmt.Printf("noroute: %v\n", ctx.FullPath())
		ctx.Redirect(http.StatusMovedPermanently, "/error")
	})

	fmt.Println(variable.Port)
	// 运行服务器
	_ = router.Run(variable.Port)
}

func loadTemplates(templateDir string) multitemplate.Renderer {
	r := multitemplate.NewRenderer()
	layouts, err := filepath.Glob(templateDir + "/layouts/*.tmpl")
	if err != nil {
		panic(err.Error())
	}
	includes, err := filepath.Glob(templateDir + "/includes/*.tmpl")
	if err != nil {
		panic(err.Error())
	}

	// 为layouts/和includes/目录生成templates map
	for _, include := range includes {
		layoutCopy := make([]string, len(layouts))
		copy(layoutCopy, layouts)
		files := append(layoutCopy, include)
		r.AddFromFiles(filepath.Base(include), files...)
	}
	return r
}
